<template>
  <el-container>
    <el-header>
      <top-bar></top-bar>
      <div class="search-box">
        <div class="search-title">
          <span>Huahui 花卉网</span>
          <span>-花之思 只为你-</span>
        </div>
      </div>
    </el-header>
    <el-main>
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="收货人" style="width:400px" prop="consignee">
          <el-input v-model="form.consignee"></el-input>
        </el-form-item>
        <el-form-item label="手机号" style="width:400px" prop="iphone">
          <el-input v-model="form.iphone"></el-input>
        </el-form-item>
        <el-form-item label="配送至" style="width:400px">
          <el-cascader
            v-model="form.selectedOptions"
            placeholder="请点击选择地址"
            :options="options"
            clearable
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" style="width:400px" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="送达时间" style="width:400px" prop="finishTime">
          <el-date-picker v-model="form.finishTime" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="贺卡留言" style="width:400px" prop="remark">
          <el-input v-model="form.remark" type="textarea" rows="4"></el-input>
        </el-form-item>
        <div class="goods-info">
          <div class="order-item-hd">核对购物清单</div>
          <div class="order-item-product-list">
            <div v-for="(item,index) in multipleSelection" :key="index" class="order-item-product-info">
              <el-image
                style="width:76px;height:83px"
                :src="item.goodsDetail.pictureUrl[0]['1']"
                fit="cover"
              ></el-image>
              <div style="margin-left:10px;display:flex;flex-direction: column;">
                <p class="order-item-product-name">{{ item.goodsDetail.goodsName }}</p>
                <div>
                  <span class="order-item-product-price">¥ {{ item.goodsDetail.price }}</span>
                  <span class="order-item-product-count">x {{ item.goodsDetail.num }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="order-item-footer">
          <div class="order-item-footer-right">
            <p class="order-item-footer-price">共<span class="pro_count">{{ totalNum }}</span>件商品，总商品金额：<span class="pro-price">¥{{ total }}</span></p>
            <div class="order-item-footer-pay">
              应付：
              <span class="pay-price ">¥{{ total }}</span>
              <div class="pay-btn" @click="submitOrders">提交订单</div>
            </div>
          </div>
        </div>
      </el-form>
    </el-main>
  </el-container>
</template>

<script>
import topBar from '../../components/topBar/index.vue'
export default {
  name: 'Pay',
  components: {
    topBar
  },
  data() {
    return {
      multipleSelection: [],
      goodsDetail: [],
      userInfo: {},
      selectedOptions: [],
      options: [],
      form: {},
      rules: {
        consignee: [
          { required: true, message: '请输入收货人', trigger: 'blur' }
        ],
        iphone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        selectedOptions: [
          { required: true, message: '请选择地址', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        finishTime: [
          { required: true, message: '请选择送达时间', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请选择送达时间', trigger: 'blur' }
        ]
      },
      cityArr: [], // 城市列表
      areaArr: [], // 区县列表
      province: '', // 省
      city: '', // 市
      area: '', // 区县,
      collect: [],
      isPayNow: false // 判断是从购物车过来还是立即购买过来
    }
  },
  computed: {
    totalNum() {
      var num = 0
      this.multipleSelection.forEach((item, index) => {
        num += item.goodsDetail.num
      })
      return num
    },
    total() {
      var tatal = 0
      this.multipleSelection.forEach((item, index) => {
        tatal += (item.goodsDetail.price * item.goodsDetail.num)
      })
      return tatal
    }
  },
  created() {
    console.log(this.$route.query)
    this.isPayNow = this.$route.query.isPayNow
    const collect = window.localStorage.getItem('collect') || []
    this.collect = JSON.parse(collect)
    this.userInfo = JSON.parse(window.localStorage.getItem('userInfo'))
    this.multipleSelection = JSON.parse(this.$route.query.multipleSelection)
    // this.goodsDetail = JSON.parse(this.$route.query.goodsDetail)
    if (this.isPayNow && !this.multipleSelection[0].goodsDetail.num) {
      this.multipleSelection[0].goodsDetail.num = 1
    }
    if (this.isPayNow != 'true') {
      const arr = [] // 不在购物车中到商品index
      this.collect.forEach((item, index) => {
        this.multipleSelection.forEach((self, num) => {
          if (item.goodsDetail.id == self.goodsDetail.id) {
            arr.push(index)
          }
        })
      })
      for (let i = arr.length - 1; i >= 0; i--) {
        this.collect.splice(arr[i], 1)
      }
    }
    this.initDistPicker()
  },
  methods: {
    // 获取地址数据
    initDistPicker() {
      console.log('initDistrictsPicker')
      const respones = require('../../assets/js/districts.json')
      const self = this
      const distData = respones
      const options = []
      // 省
      for (var provinceKy in distData['100000']) {
        const optProvinceItem = {
          value: provinceKy,
          label: distData['100000'][provinceKy]
        }
        if (distData[provinceKy]) {
          // 市
          for (var cityKy in distData[provinceKy]) {
            optProvinceItem.children = optProvinceItem.children
              ? optProvinceItem.children
              : []
            const optCityItem = {
              value: cityKy,
              label: distData[provinceKy][cityKy]
            }
            if (distData[cityKy]) {
              // 区
              for (var areaKy in distData[cityKy]) {
                optCityItem.children = optCityItem.children
                  ? optCityItem.children
                  : []
                const optAreaItem = {
                  value: areaKy,
                  label: distData[cityKy][areaKy]
                }
                optCityItem.children.push(optAreaItem)
              }
            }
            optProvinceItem.children.push(optCityItem)
          }
        }
        options.push(optProvinceItem)
      }
      self.distData = distData
      self.options = options
    },
    // 选择地区
    handleChange(value) {
      const self = this
      console.log('value=>', value)
      // 获取省名
      self.options.map((item, index) => {
        if (item.value == value[0]) {
          self.cityArr = item.children // 存储城市列表
          self.province = item.label
        }
      })
      // 获取市名
      self.cityArr.map((item, index) => {
        if (item.value == value[1]) {
          self.areaArr = item.children // 存储区县列表
          self.city = item.label
        }
      })
      // 获取区县名
      self.areaArr.map((item, index) => {
        if (item.value == value[2]) {
          self.area = item.label
        }
      })
      self.provinceCityArea = self.province + self.city + self.area
      console.log('self.provinceCityArea', self.provinceCityArea)
    },
    // 下单
    submitOrders() {
      const that = this
      const context = []
      let totalPrice = 0
      this.multipleSelection.forEach(element => {
        const obj = {}
        obj.price = element.goodsDetail.price
        obj.num = element.goodsDetail.num
        obj.goodsName = element.goodsDetail.goodsName
        obj.img = element.goodsDetail.pictureUrl[0]['1']
        obj.id = element.goodsDetail.id
        context.push(obj)
        totalPrice += (element.goodsDetail.num * element.goodsDetail.price)
      })
      this.$refs['form'].validate((valid) => {
        if (valid) { // 提交订单
          this.$confirm('确认支付?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$api.order.saveOrder({
              userId: this.userInfo.id,
              totalPrice: totalPrice,
              address: this.province + this.city + this.area + this.form.address,
              consignee: this.form.consignee,
              remark: this.form.remark,
              phone: this.form.iphone,
              finishTime: this.form.finishTime,
              context: context
            })
              .then(res => {
                console.log(res)
                if (res.data.state === 200) {
                  that.$message.success('支付成功')
                  // 支付成功后要把收藏到购物车到商品删除
                  if (this.isPayNow != 'true') {
                    window.localStorage.setItem('collect', JSON.stringify(this.collect))
                  }
                  that.$router.push('/order')
                }
              })
              .catch(() => {
                this.$message.error({
                  type: 'info',
                  message: '支付失败'
                })
              })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-container{
        width: 100%;
        height: 100%;
        min-width: 1200px;
        .el-header{
            display: flex;
            flex-direction: column;
            padding: 0;
            height: auto !important;
            min-width: 1500px;
            .search-box{
              display: flex;
              align-items: center;
              padding:20px 0 20px 200px;
              .search-title{
                display: flex;
                flex-direction: column;
                color: #fd684a;
                margin-right: 50px;
                align-items: center;
                span:nth-child(1){
                  font-size: 35px;
                }
                span:nth-child(2){
                  color: #f8bcae;
                  font-size: 18px;
                }
              }
              .search{
                width: 500px;
                ::v-deep .el-input__inner{
                border-color: #fd684a !important;
                }
                ::v-deep  .el-input-group__append{
                  background-color: #fd5e40 !important;
                  color: white;
                  border-color: #fd5e40;
                }
              }
            }
        }
        .el-main{
          background-color: #f1f3f6;
          .el-form{
            padding: 30px 20px;
            border-radius: 10px;
            background-color: white;
            width: 1200px;
            margin: 0 auto;
            min-width: 1200px;
            .goods-info{
              border-top: 1px solid #e9ecf0;
              padding-top: 20px;
              .order-item-hd{
                font-size: 17px;
                letter-spacing: 0.5px;
                font-weight: 600;
              }
              .order-item-product-list{
                background: #f7f9fa;
                margin-top: 16px;
                padding: 8px;
                display: flex;
                flex-direction: column;
                .order-item-product-name{
                    font-size: 12px;
                    margin-bottom: 8px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  }
                .order-item-product-info{
                  display: flex;
                  align-items: center;
                  margin: 10px 0;
                  .order-item-product-price{
                    font-size: 15px;
                    font-weight: 600;
                  }
                  .order-item-product-count{
                    margin-left: 32px;
                    font-size: 15px;
                    letter-spacing: 0.5px;
                  }
                }
              }
            }
            .order-item-footer{
              margin-top: 16px;
              padding: 0 8px;
              display: flex;
              justify-content: flex-end;
              .order-item-footer-right{
                display: flex;
                flex-direction: column;
                .order-item-footer-price{
                  .pro_count{
                    color: #FF734C;
                    font-weight: 600;
                    margin: 0 1px;
                  }
                  .pro-price{
                    font-weight: 600;
                  }
                }
                .order-item-footer-pay{
                  margin-top: 12px;
                  font-size: 15px;
                  display: flex;
                  align-items: center;
                  .pay-price {
                    font-size: 21px;
                    letter-spacing: 0.5px;
                    font-weight: 600;
                    color: #FF734C;
                  }
                  .pay-btn{
                    margin-left: 32px;
                    width: 200px;
                    height: 44px;
                    line-height: 44px;
                    text-align: center;
                    background: #ff734c;
                    border-radius: 27px;
                    font-size: 15px;
                    color: #ffffff;
                    border: none;
                    outline: none;
                    cursor: pointer;
                  }
                }
              }
            }
          }
        }
    }
</style>
